package com.baizhi.controller;

import com.baizhi.entity.Book;
import com.baizhi.entity.Category;
import com.baizhi.service.BooksService;
import com.baizhi.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("Category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private BooksService booksService;
    @RequestMapping("AllCategory")
    public String AllCategory(HttpServletRequest req, Integer pageNo){
        //每页显示的条数
        Integer pageCount=3;
        int pageIndex = 1;
        if (pageNo!=null){
            pageIndex=pageNo;
        }
        //调用业务层方法
        List<Category> categories = categoryService.selectCategorysByPage(pageIndex,pageCount);
        //计算总数的
        int totalCount = categoryService.selectToalCount();

        int totalPage = totalCount%pageCount==0?totalCount/pageCount:totalCount/pageCount+1;
        //将数据保存到作用域里
        req.setAttribute("categories",categories);
        //将pageNo存放在req作用域里
        req.setAttribute("pageNo",pageIndex);
        //将总条数存放在req作用域里
        req.setAttribute("totalPage",totalPage);

        return "categorylist";
    }
    @RequestMapping("deteleCategory")
    public String deleteCategory(Integer id){
        //调用业务层方法
        categoryService.deleteCategory(id);
        booksService.deletecategory(id);
        System.out.println("删除成功");
        return "forward:/Category/AllCategory.do";
    }
    @RequestMapping("addCategory")
    public String addCategory(Category category){
        //调用业务层方法
        int i = categoryService.insertCategory(category);
        if (i==1){
            System.out.println("增加成功");
            return "forward:/Category/AllCategory.do";
        }else{
            System.out.println("增加失败");
            return "forward:/Category/AllCategory.do";
        }
    }
}
